package org.example.intelligent_education.controller;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.example.intelligent_education.model.Result;
import org.example.intelligent_education.model.UserInfo;
import org.example.intelligent_education.service.UserService;
import org.example.intelligent_education.utils.JwtUtils;
import org.example.intelligent_education.utils.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public Result login(String account, String password) {
        if(account == null || account.equals("") || password == null || password.equals("")){
            return Result.fail("账号或密码为空");
        }
        UserInfo userInfo = userService.queryUserInfoByAccount(account);
        if (userInfo==null || userInfo.getUid()<0){
            return Result.fail("用户不存在");
        }

        if (!SecurityUtils.verify(password, userInfo.getPassword())){
            return Result.fail("账号或密码错误!");
        }
        //生成token, 并返回
        Map<String, Object> claim = new HashMap<>();
        claim.put("uid", userInfo.getUid());
        claim.put("account", userInfo.getAccount());
        String token = JwtUtils.genToken(claim);
        return Result.success(token);
    }

    @RequestMapping("/register")
    public Result register(String account, String password,String name) {
        if(account == null || account.equals("") || password == null || password.equals("")
        || name == null || name.equals("")){
            return Result.fail("账号或密码或用户名为空");
        }
        if(userService.queryUserInfoByAccount(account)!=null){
            return Result.fail("该账号已被注册");
        }
        String secpassword = SecurityUtils.encry(password);
        userService.addUser(account,secpassword,name);
        return Result.success("注册成功");
    }
    @RequestMapping("/recommend")
    public Result recommend(HttpServletRequest request) {
        String token = request.getHeader("user_token");
        int uid = JwtUtils.getUserIdFromToken(token);
//        log.error("uid: {}", uid);
        return Result.success(userService.recommendCourse(uid));
    }
    @RequestMapping("/boughtCourse")
    public Result boughtCourse(HttpServletRequest request) {
        String token = request.getHeader("user_token");
        int uid = JwtUtils.getUserIdFromToken(token);
        return Result.success(userService.getCoursesByUserId(uid));
    }
}



